package com.xxhui.scrolldemo.View;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

/**
 * Created by hui on 2016/7/24.
 */
public class DrawViewByScroller extends View {

    private static final String TAG = "DrawViewScroller" ;
    private int lastX;
    private int lastY;
    private int viewWidth;
    private int viewHeight;
    private Paint paint;
    private Scroller scroller;

    public DrawViewByScroller(Context context) {
        super(context);
        initRes(context);
    }

    public DrawViewByScroller(Context context, AttributeSet attrs) {
        super(context, attrs);
        initRes(context);
    }

    public void initRes(Context context){
        // 给View设置背景颜色，便于观察
        setBackgroundColor(Color.LTGRAY);
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLACK);
        paint.setTextSize(20);
        scroller = new Scroller(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();//获取以当前View为参考系的x坐标
        int y = (int) event.getY();//获取以当前View为参考系的y坐标
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                // 记录触摸点坐标
                lastX = x;
                lastY = y;

                break;
            case MotionEvent.ACTION_MOVE:
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                //scrollBy方法让View里面的内容移动，想要移动view，这个得看看view是哪个view的内容，显然当前View是viewGroup的内容，所以getparent再调用方法
                ((View) getParent()).scrollBy(-offsetX, -offsetY);
                break;
            case MotionEvent.ACTION_UP:
                View viewGroup = (View)getParent();
                scroller.startScroll(viewGroup.getScrollX(),viewGroup.getScrollY(),-viewGroup.getScrollX(),-viewGroup.getScrollX(),5000);
                invalidate();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //canvas.translate(viewWidth,viewHeight);
        canvas.drawText("scroller()",0,viewHeight/2,paint);
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        // 判断Scroller是否执行完毕
        if(scroller.computeScrollOffset()){
            ((View)getParent()).scrollTo(scroller.getCurrX(),scroller.getCurrY());
            // 通过重绘来不断调用computeScroll
            invalidate();
        }
    }
}
